<template>
	<view>
		<!-- 输入框，用于显示选中的年度 -->
		<view class="" @click="handlePicker">
			<view class="down-menu">
				<text>{{currentDate}}年</text>
				<image src="/static/images/index/down.png" class="width-12 height-12" mode=""></image>
			</view>
		</view>


		<!-- 弹出层 -->
		<Popup :show.sync="showPopup" title="选择年份">
			<view class="">
				<!-- 年度选择器 -->
				<van-picker :columns="yearColumns" :default-index="translatePicker" ref="picker" />
				<view class="self-btn full-width" hover-class="pressed" @click="handleConfirm">
					<text>确定</text>
				</view>
			</view>

		</Popup>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	import Popup from "@/components/popup/index.vue"
	export default {
		props: {
			// 双向绑定的值
			value: {
				type: [String, Number],
				default: ''
			}
		},
		components: {
			Popup
		},
		data() {
			return {
				showPopup: false, // 控制弹出层的显示
				yearColumns: [], // 年度列表
				currentDate: this.value || dayjs().format('YYYY') // 当前选中的年度
			};
		},
		computed: {
			translatePicker() {
				return this.yearColumns.findIndex(item => item.value == this.currentDate) || 0
			}
		},
		watch: {
			// 监听外部传入的 value 值变化
			value: {
				immediate: true,
				handler(val) {
					this.currentDate = val;
					if (!this.yearColumns.length) {
						this.generateYearColumns();
					}
				}

			}
		},
		methods: {
			handlePicker() {
				this.showPopup = true
			},
			// 生成年度列表
			generateYearColumns() {
				const currentYear = new Date().getFullYear();
				const years = [];
				for (let i = 1; i <= currentYear; i++) {
					years.push({
						text: `${i}年`,
						value: i.toString()
					});
				}
				this.yearColumns = years;
			},
			// handlePickerChange(picker, obj) {
			// 	this.currentYear = obj['value']
			// },
			// 确认选择
			handleConfirm(value) {
				let values = this.$refs.picker.getValues()
				this.currentYear = values[0]['value']
				this.$emit('input', this.currentYear); // 触发 input 事件，实现双向绑定
				this.showPopup = false; // 关闭弹出层
			}
		}
	};
</script>

<style scoped lang="scss">
	/* 自定义样式 */
	.down-menu {
		background: #FFFFFF;
		border-radius: 32rpx;
		border: 1rpx solid #DDE0E6;
		display: flex;
		justify-content: center;
		align-items: center;
		font-weight: 400;
		font-size: 24rpx;
		color: #202020;
		line-height: 32rpx;
		padding: 16rpx 24rpx;

		&>image {
			margin-left: 26rpx;
		}
	}
</style>